package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.pojo.dto.CustomerMergeDTO;
import com.xbongbong.paas.service.log.crm.help.OperationLogHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.parent.help.CommonPermissionHelp;
import com.xbongbong.pro.domain.entity.PersonLabelEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.label.pojo.dto.PersonLabelFindDTO;
import com.xbongbong.pro.label.pojo.dto.PersonLabelSaveDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.model.PersonLabelModel;
import com.xbongbong.saas.service.PersonLabelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author jiangren.li
 * @Title: 个人标签实现类
 * @date 2021/09/07
 */
@Service("personLabelService")
public class PersonLabelServiceImpl implements PersonLabelService {
    private static final Logger LOG = LoggerFactory.getLogger(PersonLabelServiceImpl.class);

    @Resource
    private PersonLabelModel personLabelModel;
    @Resource
    private OperationLogHelp operationLogHelp;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private CommonPermissionHelp commonPermissionHelp;

    @Override
    public Integer insert(PersonLabelEntity entity) throws XbbException {
        return null;
    }

    @Override
    public Integer updateLabelName(PersonLabelSaveDTO personLabelSaveDTO) throws XbbException {
        String corpid = personLabelSaveDTO.getCorpid();
        Long dataId = Long.valueOf(personLabelSaveDTO.getRefId());
        Integer businessType = personLabelSaveDTO.getBusinessType();
        Integer saasMark = personLabelSaveDTO.getSaasMark();
        UserVO loginUser = personLabelSaveDTO.getLoginUser();
        try {
            PaasFormDataEntityExt paasFormDataEntityExt = formDataHelp.getFormDataWithTeam(corpid, saasMark, businessType, dataId);
            VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO(loginUser, paasFormDataEntityExt);
            boolean hasDataPermission = commonPermissionHelp.checkEditPermissionWithoutTeamEdit(verifyUpdatePermissionDTO);
            if (!hasDataPermission){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), OperateTypeEnum.EDIT.getName()));
            }
            personLabelSaveDTO.setIsEdit(1);
            return saveLabelName(personLabelSaveDTO);
        } catch (XbbException e){
            throw e;
        }catch (Exception e) {
            LOG.info("新建/编辑个人标签异常" + e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.SAVE_ERROR);
        }
    }

    @Override
    public PersonLabelEntity findEntitys(PersonLabelFindDTO personLabelFindDTO) {
        String corpid = personLabelFindDTO.getCorpid();
        Integer refType = personLabelFindDTO.getRefType();
        Long refId = personLabelFindDTO.getRefId();
        String ownerId = personLabelFindDTO.getOwnerId();
        PersonLabelEntity personLabelEntity = null;
        if (Objects.nonNull(corpid) && Objects.nonNull(ownerId) && Objects.nonNull(refId) && Objects.nonNull(refType)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("refType", refType);
            param.put("refId", refId);
            param.put("ownerId", ownerId);
            personLabelEntity = personLabelModel.getByParamColumns(param);
        }
        return personLabelEntity;
    }

    private Integer saveLabelName(PersonLabelSaveDTO personLabelSaveDTO) throws XbbException {
        try {
            if (Objects.nonNull(personLabelSaveDTO)) {
                String corpid = personLabelSaveDTO.getCorpid();
                String userId = personLabelSaveDTO.getUserId();
                Integer refType = personLabelSaveDTO.getRefType();
                Integer refId = personLabelSaveDTO.getRefId();
                Integer isEdit = personLabelSaveDTO.getIsEdit();
                List<String> labelNameList = personLabelSaveDTO.getLabelNameList();
                String loginUserName = personLabelSaveDTO.getLoginUserName();

                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid", corpid);
                param.put("refType", refType);
                param.put("refId", refId);
                param.put("ownerId", userId);

                PersonLabelEntity personLabelEntity = new PersonLabelEntity();
                personLabelEntity.setCorpid(corpid);
                personLabelEntity.setOwnerId(userId);
                personLabelEntity.setRefId(refId);
                personLabelEntity.setRefType(refType);
                JSONArray objects = JSONObject.parseArray(JSONObject.toJSONString(personLabelSaveDTO.getLabelNameList()));
                personLabelEntity.setLabelName(objects);
                //先查询再更新，确保业务数据ID、业务类型、拥有者查到到的数据唯一性
                PersonLabelEntity personLabel = personLabelModel.getByParamColumns(param);
                Integer res = null;
                if (Objects.isNull(personLabel)) {
                    //新建逻辑,颜色前端定死
                    personLabelEntity.setLabelColor("#999999");
                    personLabelEntity.setFormId(personLabelSaveDTO.getFormId());
                    res =  personLabelModel.insert(personLabelEntity);
                } else {
                    //更新逻辑
                    personLabelEntity.setId(personLabel.getId());
                    res =  personLabelModel.updateLabelName(personLabelEntity);
                }
                if(isEdit!=null&&res==1){
                    operationLogHelp.updatePersonLableLog(personLabelSaveDTO,personLabel);
                }
                return res;
            }
            return null;
        } catch (Exception e) {
            LOG.info("保存个人标签异常" + e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.SAVE_ERROR);
        }
    }

    @Override
    public void mergePersonLabel(CustomerMergeDTO customerMergeDTO) throws XbbException {
        try {
            String corpid = customerMergeDTO.getCorpid();
            Long updateId = customerMergeDTO.getUpdateId();
            Long delId = customerMergeDTO.getDelId();
            Integer refType = customerMergeDTO.getBusinessType();
            String userId = customerMergeDTO.getUserId();
            Long formId = customerMergeDTO.getFormId();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("refType", refType);
            param.put("ownerId", userId);
            //查询主客户个人标签
            param.put("refId", updateId);
            PersonLabelEntity updatePersonLabel = personLabelModel.getByParamColumns(param);
            param.put("refId", delId);
            PersonLabelEntity delPersonLabel = personLabelModel.getByParamColumns(param);
            if (Objects.nonNull(delPersonLabel)) {
                //副客户存在个人标签才需要合并到主客户
                PersonLabelSaveDTO personLabelUpdateDTO = new PersonLabelSaveDTO();
                personLabelUpdateDTO.setUserId(userId);
                personLabelUpdateDTO.setCorpid(corpid);
                personLabelUpdateDTO.setRefId(Integer.valueOf(updateId.toString()));
                personLabelUpdateDTO.setRefType(refType);
                personLabelUpdateDTO.setFormId(formId);
                if (Objects.nonNull(updatePersonLabel)) {
                    JSONArray updateLabelName = updatePersonLabel.getLabelName();
                    List<String> labelNameList = updateLabelName.toJavaList(String.class);
                    //可能存在空数组
                    if (labelNameList !=null) {
                        JSONArray delLabelName = delPersonLabel.getLabelName();
                        if (delLabelName !=null && delLabelName.size() > 0) {
                            for (Object o : delLabelName) {
                                labelNameList.add(String.valueOf(o));
                            }
                        }
                        personLabelUpdateDTO.setLabelNameList(labelNameList);
                    }
                } else {
                    JSONArray delLabelName = delPersonLabel.getLabelName();
                    List<String> labelNameList = delLabelName.toJavaList(String.class);
                    personLabelUpdateDTO.setLabelNameList(labelNameList);
                }
                personLabelUpdateDTO.setIsEdit(2);
                saveLabelName(personLabelUpdateDTO);
            }
        } catch (Exception e) {
            LOG.info("合并客户失败" + e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, ErrorMessageConstant.SAVE_ERROR);
        }
    }
}
